package cn.mygweb.common.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import cn.mygweb.admin.modules.sys.pojo.User;
import cn.mygweb.admin.modules.sys.service.UserService;

/** 
* <p>Title: SysUserRealm.java</p>
* <p>Description: 自定义Realm</p>  
* @author gxb 
* @date 2019年6月2日 
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.mygweb.cn</p> 
*/
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;

	/**
	 * <p>Title: doGetAuthorizationInfo</p>
	 * <p>Description: 执行授权逻辑</p>
	 * @param principals
	 * @return
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		//给资源进行授权
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		//添加资源的授权字符串，查询用户的权限信息并加入列表
		Subject subject = SecurityUtils.getSubject();
		User user = (User)subject.getPrincipal();
		List<String> permList = userService.queryPermsByUserId(user.getId());
		if(permList != null && permList.size() > 0) {
			for (String perm : permList) {
				info.addStringPermission(perm);
			}
		}
		return info;
	}

	/**
	 * <p>Title: doGetAuthenticationInfo</p>
	 * <p>Description: 执行认证逻辑</p>
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//编写shiro判断逻辑，判断用户名和密码
		UsernamePasswordToken t = (UsernamePasswordToken)token;
		
		//从数据库中查询用户是否存在
		User user = userService.findByUsername(t.getUsername());

		//1.判断用户名
		if(user == null) {//用户不存在
			return null;//shiro底层会抛出UnknownAccountException
		}
		if(user != null && user.getStatus() != 0) {//用户状态不是正常状态，可能是注销或者停用
			return null;
		}
		//2.判断密码，此处第一个参数 user 是提供给doGetAuthorizationInfo授权管理使用的
		return new SimpleAuthenticationInfo(user, user.getPassword(), "");
	}

}
